//
//  ALPPlayViewController.m
//  AlpFM
//
//  Created by KING on 16/1/26.
//  Copyright © 2016年 Alp. All rights reserved.
//

#import "ALPPlayViewController.h"
#import <AFNetworking.h>
#import "ALPPlayModel.h"
#import "ALPSingleModel.h"
#import <AVFoundation/AVFoundation.h>
#import "ALPPlayView.h"
#import "UIImage+Blur.h"
#import "UIImageView+WebCache.h"
#import "ALPDateBaseManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "ALPPlayListViewController.h"
#define FULL_SCREEN [[UIScreen mainScreen] bounds]
//沙盒路径
#define  DOCUMENT  [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
@interface ALPPlayViewController ()
//view
@property (nonatomic, strong) ALPPlayView *musicView;
@property (nonatomic, strong) UIButton *returnButton;
@property (nonatomic, strong) UIButton *playButton;
@property (nonatomic, strong) UIButton *lastButton;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) UIButton *listButton;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UISlider *progressSlider;
@property (nonatomic, strong) UISlider *volumeSlider;
@property (nonatomic, strong) ALPSingleModel *playerModel;
@property (nonatomic, strong) UIButton *xunButton;


@end

@implementation ALPPlayViewController
//创建单例
+(instancetype)sharePlayerViewController
{
    
    static ALPPlayViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[ALPPlayViewController alloc] init];
        
    });
    
    return player;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//     Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    //创建音乐对象
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;

    
    //显示区视图
    self.musicView = [[ALPPlayView alloc] initWithFrame:FULL_SCREEN];
    [self.view addSubview:self.musicView];
    
    //控制区的视图
    [self p_addButtomView];
    
    //设置按钮
    self.returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.returnButton.frame = CGRectMake(10, 30, 40, 40);
    [self.returnButton setImage:[UIImage imageNamed:@"btn_back_n@3x"] forState:UIControlStateNormal];
//    self.returnButton.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.returnButton];
    [self.returnButton addTarget:self action:@selector(returnAction:) forControlEvents:UIControlEventTouchUpInside];

    //下载完成后执行每秒读取
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(trackAction) userInfo:nil repeats:YES];
    [self.timer setFireDate:[NSDate distantFuture]];
    //菊花
//    [GiFHUD setGifWithImageName:@"hold.gif"];
//    [GiFHUD show];

//    self.listButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.listButton.frame = CGRectMake(200, 500, 40, 40);
//    self.listButton.backgroundColor = [UIColor yellowColor];
//    [self.view addSubview:self.listButton];
//    [self.listButton addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self playMusic];
    

    
}
#pragma mark - 创建播放控制区的view
- (void)p_addButtomView{
    
    //播放器底层的view
    UIImageView *baseMusicView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0.67*SCREEN_HEIGHT+30, SCREEN_WIDTH, 0.15*SCREEN_HEIGHT)];
    baseMusicView.userInteractionEnabled = YES;
    [self.view addSubview:baseMusicView];
    
    //进度条加载到viewController上了
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, -6, SCREEN_WIDTH, 0.05*SCREEN_WIDTH)];
    self.progressSlider.value = 0.0;
    [baseMusicView addSubview:self.progressSlider];
    
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"sliderImage.png"] forState:UIControlStateHighlighted];
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"sliderImage.png"] forState:UIControlStateNormal];
    [self.progressSlider addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
    
    //分钟的lable
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH *0.7, -0.08*SCREEN_WIDTH, SCREEN_WIDTH *(1-0.7), 0.07*SCREEN_WIDTH)];
    self.timeLabel.text = @"00:00/00:00";
    self.timeLabel.font = [UIFont systemFontOfSize:0.037*SCREEN_WIDTH];
    self.timeLabel.textColor = [UIColor colorWithRed:0.614 green:0.586 blue:0.389 alpha:1.000];
    [baseMusicView addSubview:self.timeLabel];
    
    //播放和暂停按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(0, 0, 75, 75);
    self.playButton.center = CGPointMake(SCREEN_WIDTH / 2.0, 0.075*SCREEN_HEIGHT);
    [baseMusicView addSubview:self.playButton];
    [self.playButton setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n_p@3x"] forState:UIControlStateNormal];
//    self.playButton.backgroundColor = CLEAR;
    [self.playButton addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //下一曲按钮
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(0, 0, 60, 60);
    self.nextButton.center = CGPointMake(SCREEN_WIDTH * 0.7, 0.075*SCREEN_HEIGHT);
    [baseMusicView addSubview:self.nextButton];
    [self.nextButton setBackgroundImage:[UIImage imageNamed:@"toolbar_next_h_p@3x"] forState:UIControlStateNormal];
//    self.nextButton.backgroundColor = CLEAR;
    [self.nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //上一曲按钮
    self.lastButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.lastButton.frame = CGRectMake(0, 0, 60, 60);
    self.lastButton.center = CGPointMake(SCREEN_WIDTH * 0.3, 0.075*SCREEN_HEIGHT);
    [baseMusicView addSubview:self.lastButton];
    [self.lastButton setBackgroundImage:[UIImage imageNamed:@"toolbar_prev_n_p@3x"] forState:UIControlStateNormal];
    [self.lastButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //播放列表
    self.listButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.listButton.frame = CGRectMake(0, 0, 30, 30);
    self.listButton.center = CGPointMake(SCREEN_WIDTH * 0.1, 0.075*SCREEN_HEIGHT);
//    self.listButton.backgroundColor = [UIColor orangeColor];
    [baseMusicView addSubview:self.listButton];
    [self.listButton setBackgroundImage:[UIImage imageNamed:@"iconfont-liebiao"] forState:UIControlStateNormal];
    [self.listButton addTarget:self action:@selector(listButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    self.xunButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.xunButton.frame = CGRectMake(0, 0, 30, 30);
    self.xunButton.center = CGPointMake(SCREEN_WIDTH *0.9, 0.075*SCREEN_HEIGHT);
    [baseMusicView addSubview:self.xunButton];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"dan"]) {
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-danquxunhuan.png"] forState:UIControlStateNormal];
    }
    else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"sui"]) {
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-wodesuijibofang"] forState:UIControlStateNormal];
      
    }
    else{
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xunhuan.png"] forState:UIControlStateNormal];
       
    }
    
   
    [self.xunButton addTarget:self action:@selector(xunAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
}
-(void)xunAction:(UIButton *)btn{
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"dan"]) {
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-wodesuijibofang"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@"sui" forKey:@"xun"];
        
    }
    else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"sui"]) {
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-xunhuan.png"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@"lie" forKey:@"xun"];
    }
    else{
        [self.xunButton setBackgroundImage:[UIImage imageNamed:@"iconfont-danquxunhuan"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@"dan" forKey:@"xun"];
    }
}
-(void)returnAction:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}
-(void)playAction:(UIButton *)btn{
//    NSLog(@"%d", self.player.state);
    
    if (self.player.state == STKAudioPlayerStatePaused) {
        
//        NSLog(@"暂停");
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n_p@3x"] forState:UIControlStateNormal];

        [self.player resume];//继续
        [self.timer setFireDate:[NSDate distantPast]];
//        NSLog(@"%@",self.timer);

    }else if (self.player.state == STKAudioPlayerStatePlaying) {
        
//        NSLog(@"播放");

        [self.playButton setBackgroundImage:[UIImage imageNamed:@"toolbar_play_n_p@2x"] forState:UIControlStateNormal];
        [self.player pause];
        [self.timer setFireDate:[NSDate distantFuture]];

    }
    else {
        //去下载数据
//        NSLog(@"其他执行");
        [self playMusic];
    }
}
#pragma mark - 上一曲按钮
- (void)backButtonAction:(UIButton *)btn{
    //    NSLog(@"列表数%ld 歌曲位子%ld ID%@", self.allMusicArray.count, self.indexRow, self.song_ID);
    
    self.indexRow = self.indexRow - 1;
    if (self.indexRow < 0) {
        self.indexRow = self.allMusicArray.count - 1;
    }
    ALPSingleModel *model = [self.allMusicArray objectAtIndex:self.indexRow];
    self.song_ID = model.trackId.intValue; //self.song_ID会调用set方法, 会刷新数据
}
-(void)nextAction:(UIButton *)btn{
    
    
    if (self.allMusicArray.count == 0) {
        return;
    }
    
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"sui"]) {
        NSInteger ger = arc4random() % (self.allMusicArray.count -1 +1) +1;

        self.indexRow = ger;
    }
    
    else{
        //+1取余会获得下一曲的id ,如果是最后一曲,下标就会变成0, 会获取到第一歌的ID也就是重头播放了
        self.indexRow = (self.indexRow + 1) % self.allMusicArray.count;
        
    }

    //+1取余会获得下一曲的id ,如果是最后一曲,下标就会变成0, 会获取到第一歌的ID也就是重头播放了
//    self.indexRow = (self.indexRow + 1) % self.allMusicArray.count;
    
    if (self.indexRow < self.allMusicArray.count) {
        
        ALPSingleModel *model = [self.allMusicArray objectAtIndex:self.indexRow];
        self.song_ID = model.trackId.intValue; //self.song_ID会调用set方法, 会刷新数据
    } else {
        [self playMusic];
    }
    self.progressSlider.maximumValue = 1;
    self.progressSlider.value = 0;
    
}
-(void)stopAction:(UIButton *)btn{
    [self.player stop];
    [self.player clearQueue];//清空音频队列
    [self.timer invalidate];//定时器停止
    self.timer = nil;
    self.progressSlider.value = 0.f;
    [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
}
#pragma mark - 播放列表
- (void)listButtonAction:(UIButton *)btn{
    ALPPlayListViewController *playList = [[ALPPlayListViewController alloc] init];
    UINavigationController *navc = [[UINavigationController alloc] initWithRootViewController:playList];
    
    playList.song_ID = self.song_ID;
    
    
    playList.listArray = self.allMusicArray;
    playList.index = self.indexRow;
    
    navc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    [self presentViewController:navc animated:YES completion:^{
        
    }];
    
}

-(void)progressAction:(UISlider *)sender{
    if (self.player) {
        
        [self.player seekToTime:sender.value];
        
    }
}
//-(void)volumeAction:(UISlider *)sender{
//    self.player.volume = sender.value;
//    NSLog(@"volume = %f",self.player.volume);
//}
-(void)setSong_ID:(NSInteger)song_ID{
    _song_ID = song_ID;
//    [self playMusic];
    [self playMusicUrl];
    
}

- (void)playMusic
{

    //拼接路径
//    NSString *arrayPath = [DOCUMENT stringByAppendingPathComponent:@"musicListData.txt"];
    
//    [string writeToFile:arrayPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//    NSString *str = [[NSString alloc] initWithContentsOfFile:arrayPath encoding:NSUTF8StringEncoding error:nil];
//    _song_ID = string.intValue;
//    NSLog(@"paly");
//    NSLog(@"%@",str);
//    NSString *song = [[NSUserDefaults standardUserDefaults]objectForKey:@"str"];
//    _song_ID = song.intValue;
//    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"str"]);
    
    
//    NSString *string = [NSString stringWithFormat:@"%ld", (long)_song_ID];
//    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"str"];
//    [self playMusicUrl:string];
//    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"str"]);
}
-(void)playMusicUrl{
    
    NSString *string = [NSString stringWithFormat:@"%ld", (long)_song_ID];
    [[NSUserDefaults standardUserDefaults] setObject:string forKey:@"str"];
    NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"str"];
    
    NSString *url = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/%@?device=android", str];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [session GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        //        NSLog(@"成功");
        NSMutableDictionary *dictionary = responseObject;
        self.playerModel = [[ALPSingleModel alloc] init];
        [self.playerModel setValuesForKeysWithDictionary:dictionary];
//        NSLog(@"p%@",self.playerModel.playUrl64);
        //音乐地址
        //        NSLog(@"%@", playerModel.playUrl64);
        [self.player play:self.playerModel.playUrl64];
        //图片
        NSURL *url = [NSURL URLWithString:self.playerModel.coverLarge];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        self.musicView.backgroundImage.image = [image boxblurImageWithBlur:1];
        [self.musicView.musicImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"min"]];
        //title
        self.musicView.titleLabel.text = self.playerModel.title;
        self.navigationItem.titleView = self.musicView.titleLabel;
        
        //作者的头像
        NSURL *urled = [NSURL URLWithString:self.playerModel.smallLogo];
        [self.musicView.edictorImage sd_setImageWithURL:urled placeholderImage:[UIImage imageNamed:@"min"]];
        //作者的title
        self.musicView.edictorLabel.text = self.playerModel.nickname;
        //作者的subTitle
        self.musicView.edictorSubLabel.text = self.playerModel.albumTitle;
        
        //************  通知按钮改变图片,传过去一个url ************
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:[NSURL URLWithString:self.playerModel.coverLarge]];
        
        //        NSLog(@"是不是应该在这里面执行历史存储呢?");
        //        NSLog(@"当前时长:%lf", self.player.progress);
        //        NSLog(@"id:%@", self.song_ID);
        [self.timer setFireDate:[NSDate distantPast]];
        
        //将播放记录存入数据库
        NSMutableArray *array = [[ALPDateBaseManager shareFMDB] seleteHistory];
        NSMutableArray *idArray = [NSMutableArray array];
        
        for (ALPHistoryModel *model in array) {
            [idArray addObject:model.song_ID];
        }
        if ([idArray containsObject:str]) {
            [[ALPDateBaseManager shareFMDB] deleteHistoryWithSong_ID:str];
            [[ALPDateBaseManager shareFMDB] insertHistory:self.playerModel andLastTime:nil andSong_ID:str];
        } else {
            [[ALPDateBaseManager shareFMDB] insertHistory:self.playerModel andLastTime:nil andSong_ID:str];
        }
        
        
        
        //        [GiFHUD dismiss];
        
        //        [netWorkManager stopMonitoring];
        //
        /*
         
         //
         //    self.navigationItem.title = playData.title;
         //
         //   self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
         */
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        NSLog(@"失败");        
        
    }];
    
    

}
-(void)trackAction{
    //总时长/ 当前进度
    self.progressSlider.maximumValue = self.player.duration;
    self.progressSlider.value = self.player.progress;
    
    //当前时长
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前的分
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前秒
    
    //总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总的分
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总得秒
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    
    //播放时就会让按钮改变
    if (self.player.state == STKAudioPlayerStatePlaying) {
        //如果播放状态
        [self.playButton setBackgroundImage:[UIImage imageNamed:@"toolbar_pause_n_p@3x"] forState:UIControlStateNormal];
    }
    
    //播放到最后自动跳到下一曲
    //    NSLog(@"%lf--%lf", self.progtessSlider.maximumValue,self.progtessSlider.value);
    
    if (self.progressSlider.maximumValue - self.progressSlider.value < 3 && self.progressSlider.maximumValue != 0) {
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"xun"] isEqualToString:@"dan"]) {
            [self playMusicUrl];
            NSLog(@"dan");
        }
        
        else{
            [self nextAction:nil];
            
        }
        
        self.progressSlider.maximumValue = 1;
        self.progressSlider.value = 0;
        NSLog(@"播放完毕");
        
        
    }
    
    

    
    
    
    
    //记录最后播放时间
    NSString *time = [NSString stringWithFormat:@"%lf", self.player.progress];
    
    if ([[ALPDateBaseManager shareFMDB] seleteHistory]) {
        
        [[ALPDateBaseManager shareFMDB] upDataHistoryLastTime:time WithSongID:[NSString stringWithFormat:@"%ld", (long)self.song_ID]];
    }
   
    //标题
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
//        [dict setObject:self.playerModel.title forKey:MPMediaItemPropertyTitle];
    
    //图片
//        if (self.playerModel.coverLarge.length != 0) {
//            NSURL *url = [NSURL URLWithString:self.playerModel.coverLarge];
//            NSData *data = [NSData dataWithContentsOfURL:url];
//            UIImage *image = [UIImage imageWithData:data];
//            MPMediaItemArtwork * mArt = [[MPMediaItemArtwork alloc] initWithImage:image];
//            [dict setObject:mArt forKey:MPMediaItemPropertyArtwork];
//        }
    
    //进程
    
//        [dict setObject:[NSNumber numberWithInt:self.player.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
//        [dict setObject:[NSNumber numberWithInt:self.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];
//        [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
    
    
}

-(void)track
{
//    NSLog(@"====%@",self.player);
    
    self.progressSlider.maximumValue = self.player.duration;//音乐总共时长
    self.progressSlider.value = self.player.progress;//当前进度
    
    //当前时长progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
//    NSLog(@"proMin = %ld proSec = %ld",proMin, proSec);
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
